package com.wswy.wzcx.ui.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextPaint;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.api.SimpleResultObserver;
import com.che.libcommon.ui.BaseFragment;
import com.che.libcommon.utils.ToastUtils;
import com.che.libcommon.utils.optional.function.Consumer;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.model.DataCenter;
import com.wswy.wzcx.model.UserMode;
import com.wswy.wzcx.model.resp.CaptchaData;
import com.wswy.wzcx.module.validator.ValidatorResult;
import com.wswy.wzcx.ui.activity.ITestValidator;
import com.wswy.wzcx.ui.other.AndroidUtilities;
import com.wswy.wzcx.ui.other.LayoutHelper;
import com.wswy.wzcx.ui.other.DownTimer;
import com.wswy.wzcx.ui.activity.PwdActivity;
import com.wswy.wzcx.widget.VerCodeView;

/**
 * Created by wangduheng26 on 2018/1/22.
 * wangduheng26@gmail.com
 * 检查验证码
 */

public class PreSetupPwdFragment extends BaseFragment {
    public static final String TAG = "PreSetupPwdFragment";
    public static final int SMS_TYPE_BIND = 0X03;
    TextView tvPhone;
    UserMode mode;
    VerCodeView verCodeView;
    TextView tvRequestSendCode;

    public static PreSetupPwdFragment newInstance() {

        Bundle args = new Bundle();

        PreSetupPwdFragment fragment = new PreSetupPwdFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        DataCenter center = DataCenter.get();
        if (center.hasLogin()) {
            mode = center.getUserMode();
        }
    }


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Context context = container.getContext();
        LinearLayout layout = new LinearLayout(context);
        layout.setOrientation(LinearLayout.VERTICAL);
        layout.setPadding(0, AndroidUtilities.dp(40), 0, 0);

        TextView textView = new TextView(context);
        textView.setText(R.string.please_input_ver_code);
        textView.setGravity(Gravity.CENTER_HORIZONTAL);
        layout.addView(textView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));

        tvPhone = new TextView(context);
        tvPhone.setGravity(Gravity.CENTER_HORIZONTAL);
        tvPhone.setTextSize(TypedValue.COMPLEX_UNIT_SP, 24);
        tvPhone.setTextColor(ContextCompat.getColor(context, R.color.gray20));
        TextPaint tp = tvPhone.getPaint();
        tp.setFakeBoldText(true);
        LinearLayout.LayoutParams layoutParams = LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT);
        LayoutHelper.setMargin(layoutParams, 0, 10, 0, 30);
        layout.addView(tvPhone, layoutParams);

        verCodeView = new VerCodeView(context);
        layout.addView(verCodeView, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT));
        verCodeView.setInputCompleteListener(new VerCodeView.InputCompleteListener() {
            @Override
            public void inputComplete() {
                checkVerCode();
            }

            @Override
            public void invalidContent() {

            }
        });

        tvRequestSendCode = new TextView(context);
        tvRequestSendCode.setText(R.string.fetch_ver_code);
        tvRequestSendCode.setGravity(Gravity.CENTER_HORIZONTAL);
        layout.addView(tvRequestSendCode, LayoutHelper.setMargin(LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT), 0, 30, 0, 0));
        return layout;
    }

    private void checkVerCode() {
        final String code = verCodeView.getEditContent();
        if (!TextUtils.isEmpty(code) && !isFinish()) {
            ((PwdActivity) getActivity()).replaceFragment(SetupPwdFragment.newInstance(mode.mobile,code));
        }

    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (mode != null) {
            tvPhone.setText(mode.mobile);


            if (getActivity() instanceof ITestValidator){

                Api.get().getCaptcha().subscribe(new ApiOptionalResultObserver<CaptchaData>(){

                    @Override
                    protected void onApiResult(@Nullable CaptchaData data) {
                        start(data);
                    }

                    @Override
                    protected void onApiError(@Nullable BaseResult result) {
                        toastErrorMsg(result);
                    }
                });



            }


        }

    }

    private void start(CaptchaData data){
        ((ITestValidator) getActivity()).getValidator(data).startVerify(new Consumer<ValidatorResult>() {
            @Override
            public void consume(ValidatorResult value) {

                if (value != null){
                    sendCode(value);
                }else {
                    ToastUtils.showText("验证失败，请返回重试。");
                }

            }
        });
    }


    private void sendCode(ValidatorResult ticket){
        Api.get().fetchPhoneVer(SMS_TYPE_BIND, mode.mobile,ticket)
            .subscribe(new ApiOptionalResultObserver<Boolean>() {


                @Override
                protected void onApiResult(@Nullable Boolean aBoolean) {
                    showToast("验证码已发送你的手机上");
                    startTimer();
                }

                @Override
                protected void onApiError(BaseResult result) {
                    toastErrorMsg(result);
                }
            });
    }

    private void startTimer() {
        new DownTimer(60, 1, tvRequestSendCode).start();
        verCodeView.findFocus();
    }

    @Override
    public String getFragmentTitle() {
        return "设定密码";
    }
}
